<template>
    <div class="follow-list-page">
        <!-- 顶部导航栏 -->
        <HeaderNav active-menu="network" />

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 左侧边栏 -->
            <Sidebar :active-sidebar="activeSidebar" @sidebar-select="handleSidebarSelect" />

            <!-- 右侧内容区域 -->
            <main class="follow-list-main">
                <div class="follow-list-container">
                    <!-- 页面标题和切换 -->
                    <div class="page-header">
                        <h1>{{ pageTitle }}</h1>
                        <div class="tab-switch">
                            <el-button :type="activeTab === 'following' ? 'primary' : ''"
                                @click="switchTab('following')">
                                关注列表
                            </el-button>
                            <el-button :type="activeTab === 'followers' ? 'primary' : ''"
                                @click="switchTab('followers')">
                                粉丝列表
                            </el-button>
                        </div>
                    </div>

                    <!-- 用户列表 -->
                    <div class="users-list">
                        <div v-if="loading && users.length === 0" class="loading-state">
                            <el-icon class="is-loading">
                                <Loading />
                            </el-icon>
                            <span>加载中...</span>
                        </div>

                        <template v-else>
                            <UserCard v-for="user in users" :key="user.user_id" :user="user" class="follow-user-card" />

                            <div v-if="users.length === 0" class="empty-state">
                                <el-empty :description="emptyText" />
                            </div>

                            <!-- 加载更多 -->
                            <div v-if="hasMore" class="load-more">
                                <el-button :loading="loading" :disabled="loading" @click="loadMore" text>
                                    {{ loading ? '加载中...' : '加载更多' }}
                                </el-button>
                            </div>

                            <div v-else-if="users.length > 0" class="no-more">
                                没有更多用户了
                            </div>
                        </template>
                    </div>
                </div>
            </main>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useFollowsStore } from '@/stores/follow'
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Sidebar from '@/components/layout/Sidebar.vue'
import UserCard from '@/components/network/UserCard.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const followsStore = useFollowsStore()

const users = ref([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(20)
const activeTab = ref('following')
const activeSidebar = ref('network')

const userId = computed(() => route.params.userId)
const pageTitle = computed(() => {
    return activeTab.value === 'following' ? '关注列表' : '粉丝列表'
})
const emptyText = computed(() => {
    return activeTab.value === 'following' ? '暂无关注用户' : '暂无粉丝'
})

// 侧边栏导航
const handleSidebarSelect = (index) => {
    activeSidebar.value = index
    switch (index) {
        case 'dashboard':
            router.push('/')
            break
        case 'social':
            router.push('/social')
            break
        case 'circles':
            router.push('/circle')
            break
        case 'chat':
            router.push('/chat')
            break
        case 'lost-found':
            router.push('/lost-and-found')
            break
        case 'second-hand':
            router.push('/second-hand')
            break
        case 'recruitment':
            router.push('/recruitment')
            break
        default:
            ElMessage.success(`当前已是在 ${index}页面`)
    }
}

// 切换标签
const switchTab = (tab) => {
    activeTab.value = tab
    page.value = 1
    users.value = []
    loadUsers(true)
}

// 加载用户列表
const loadUsers = async (reset = false) => {
    if (loading.value) return

    try {
        loading.value = true

        if (reset) {
            page.value = 1
            users.value = []
        }

        const params = {
            page: page.value,
            pageSize: pageSize.value
        }

        let response
        if (activeTab.value === 'following') {
            response = await followsStore.fetchFollowingList(userId.value, params)
            if (response.code === 0) {
                // 处理关注列表数据格式
                users.value = followsStore.followingList.map(item => {
                    // 关注列表返回的数据可能是 { follow_id, user } 格式
                    return item.user || item
                })
            }
        } else {
            response = await followsStore.fetchFollowersList(userId.value, params)
            if (response.code === 0) {
                // 处理粉丝列表数据格式
                users.value = followsStore.followersList.map(item => {
                    // 粉丝列表返回的数据可能是 { follower_id, user } 格式
                    return item.user || item
                })
            }
        }

        if (response.code === 0) {
            // 检查是否还有更多数据
            hasMore.value = activeTab.value === 'following' ?
                followsStore.hasMoreFollowing : followsStore.hasMoreFollowers
        }
    } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载用户列表失败')
    } finally {
        loading.value = false
    }
}

// 加载更多
const loadMore = () => {
    page.value += 1
    loadUsers(false)
}

// 监听路由参数变化
watch(() => route.query.type, (newType) => {
    if (newType && ['following', 'followers'].includes(newType)) {
        activeTab.value = newType
        page.value = 1
        users.value = []
        loadUsers(true)
    }
})

onMounted(() => {
    // 从路由参数获取初始标签
    const type = route.query.type
    if (type && ['following', 'followers'].includes(type)) {
        activeTab.value = type
    }
    loadUsers(true)
})
</script>

<style scoped>
.follow-list-page {
    min-height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
}

.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.follow-list-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    margin-left: 280px;
}

.follow-list-container {
    max-width: 800px;
    margin: 0 auto;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
}

.page-header h1 {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin: 0;
}

.tab-switch {
    display: flex;
    gap: 10px;
}

.users-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.follow-user-card {
    margin-bottom: 0;
}

.loading-state {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #999;
    gap: 8px;
}

.empty-state {
    padding: 40px 0;
}

.load-more {
    text-align: center;
    padding: 20px;
}

.no-more {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .follow-list-main {
        margin-left: 240px;
        padding: 16px;
    }

    .page-header {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }
}
</style>